<template>
  <el-card shadow="hover">
    <template #header>
      <div class="flex justify-between">
        <span class="text-sm">{{ title }}</span>
        <el-tag effect="plain" class="mr-1">
          {{ tip }}
        </el-tag>
      </div>
    </template>
    <el-row :gutter="20">
      <div ref="el" id="pie" style="width: 100%;height: 300px;"></div>
    </el-row>
  </el-card>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue'
// import { unify, divide } from '../flowdata'
import * as echarts from 'echarts'
// import {getAttackType,getLiuLiang} from '~/api/test.js'
import {useResizeObserver} from '@vueuse/core'
import {unify} from '../utils'
import {getAttackType,getLiuLiang} from '~/api/base.js'
const outside = defineProps({
  title: String,
  tip: String,
  // btns: Array
})

let myChart = null

onMounted(() => {
  var chartDom = document.getElementById('pie')
  if (chartDom) {
    myChart = echarts.init(chartDom)
    getData()
  }
})

onBeforeUnmount(() => {
  if (myChart) echarts.dispose(myChart)
})

function getData() {
  const ec_data = []
  
  getLiuLiang().then(res => {
    console.log('level_pie_res', res)
    const rdata = res.results
    // console.log('rdata', rdata)
    const rdata2 = unify(rdata)
    // console.log('rdata2', rdata2)

    const rd3 = rdata2.threat_level
    console.log('rd3', rd3)

    // 创建一个空对象来存储结果
    const result = {};
    let item = null
    // 遍历数组，对每个元素进行计数
    for (let i = 0; i < rd3.length; i++) {
      item = rd3[i];

      // 如果对象中已经存在该元素，则增加计数
      if (result[item]) {
        result[item]++;
      }
      // 否则，在对象中创建该元素，并将计数初始化为1
      else {
        result[item] = 1;
      }
    }
    // 将结果转换为所需的格式
    for (let key in result) {
      if (key === 'None') {
        ec_data.push({name: '无危', value: result[key]});
      } else {
        ec_data.push({name: 'Level '+key, value: result[key]});
      }
    }

    // console.log('ec_data', ec_data)
    myChart.setOption(option)
  })
    .finally(() => {
      myChart.hideLoading()
    })
  let option = {
    title: {
      // text: outside.title,
      // subtext: outside.tip,
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        data: ec_data,
        // [{ value: 1, name: 'Search Engine' }],
        itemStyle: {
        borderRadius: 8,
        borderColor: '#fff',
        borderWidth: 1
      },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  myChart.setOption(option)
}

// vueuse 里面的 useResizeObserve   在使用myChart.resize() 重新自己设定大小
const el = ref(null)
useResizeObserver(el, entries => myChart.resize())
</script>
  
